package com.chcit.mobile.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.mobile.app.contains.HttpMethodContains;
import com.chcit.mobile.app.utils.SharedPreUtils;
import com.chcit.mobile.common.DataKeys;
import com.chcit.mobile.di.component.DaggerLoginComponent;
import com.chcit.mobile.helper.DialogHelper;
import com.chcit.mobile.helper.UpdateAppHttpUtil;
import com.chcit.mobile.mvp.presenter.LoginFragmentPresenter;
import com.chcit.mobile.mvp.ui.activity.HomeActivity;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.base.app.ConfigKeys;
import com.jess.arms.base.app.Quick;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.chcit.mobile.di.module.LoginModule;
import com.chcit.mobile.mvp.contract.LoginContract;
import com.chcit.mobile.mvp.presenter.LoginPresenter;

import com.chcit.mobile.R;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.vector.update_app.listener.IUpdateDialogFragmentListener;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class LoginFragment extends BaseFragment<LoginFragmentPresenter> implements LoginContract.FragmentView {

    public static LoginFragment newInstance() {
        LoginFragment fragment = new LoginFragment();
        return fragment;
    }
    @BindView(R.id.login_picture)
    ImageView loginPicture;
    @BindView(R.id.account)
    EditText account;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.ll_user_info)
    LinearLayoutCompat llUserInfo;
    @BindView(R.id.login)
    Button login;


    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerLoginComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .loginModule(new LoginModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_login, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        account.addTextChangedListener(textWatcher);
        password.addTextChangedListener(textWatcher);
        account.setText(SharedPreUtils.getInstance().getString(DataKeys.USERNAME.name(),""));
        //检测更新
        QuickLoader.showLoading(mContext);
        new UpdateAppManager
                .Builder()
                //当前Activity
                .setActivity(getActivity())
                //更新地址
                .setUpdateUrl(HttpMethodContains.update_url)
                //实现httpManager接口的对象
                .showIgnoreVersion()
                .setHttpManager(new UpdateAppHttpUtil())
                .setUpdateDialogFragmentListener(new IUpdateDialogFragmentListener() {
                    @Override
                    public void onUpdateNotifyDialogCancel(UpdateAppBean updateApp) {

                    }
                })

                .build()
                .checkNewApp(new UpdateCallback(){
                    @Override
                    protected void noNewApp(String error) {


                    }

                    @Override
                    protected void onAfter() {
                        QuickLoader.stopLoading();
                    }
                })
        //.update()
        ;
    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
    }

    @Override
    public void toHomeActivity() {

        DialogHelper.showWareSelect(mContext, (dialog, itemView, which, text) -> {

            Quick.withConfigure(ConfigKeys.WAREHOUSE,which);
            startActivity(new Intent(mContext,HomeActivity.class));
            if( getActivity()!= null){
                getActivity().finish();
            }
            return true;
        });


    }

    @OnClick(R.id.login)
    void onClickSignIn() {
        String userName = account.getText().toString();
        String passWord = password.getText().toString();
        mPresenter.login(userName,passWord);
    }

    private int mEditTextHaveInputCount;
    private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            /** EditText内容改变之后 内容为空时 个数减一 按钮改为不可以的背景*/
            if (TextUtils.isEmpty(s)) {
                mEditTextHaveInputCount--;
                login.setEnabled(false);
            }
        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            /** EditText最初内容为空 改变EditText内容时 个数加一*/
            if (TextUtils.isEmpty(s)) {

                mEditTextHaveInputCount++;
                /** 判断个数是否到达要求*/
                /* EditText总个数
                 */ /**
                 * EditText总个数
                 */int EDITTEXT_AMOUNT = 2;
                if (mEditTextHaveInputCount == EDITTEXT_AMOUNT) {
                    login.setEnabled(true);
                }
            }

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };


}
